package com.develop.data.loan.model;

import com.develop.data.base.model.IdSpaceTimeRecord;
import com.develop.data.loan.jpa.attribute.converter.LoanContractAttributeConverter;
import com.develop.data.loan.jpa.attribute.converter.LoanMoneyAmountAttributeConverter;
import lombok.*;
import lombok.experimental.SuperBuilder;
import org.javamoney.moneta.Money;

import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "LOAN_REPAYMENT")
@SuperBuilder
@Getter
@Setter
@RequiredArgsConstructor
@AllArgsConstructor
public class LoanRepayment extends IdSpaceTimeRecord {

    /*动帐日*/
    public LocalDateTime cursor;
    /*还款金额*/
    @Builder.Default
    @Convert(converter = LoanMoneyAmountAttributeConverter.class)
    public MonetaryAmount repaymentAmount = Money.zero(Monetary.getCurrency("CNY"));
    /*还款金额中还利息的部分*/
    @Builder.Default
    @Convert(converter = LoanMoneyAmountAttributeConverter.class)
    public MonetaryAmount installmentInterest = Money.zero(Monetary.getCurrency("CNY"));
    /*还款金额中还逾期利息的部分*/
    @Builder.Default
    @Convert(converter = LoanMoneyAmountAttributeConverter.class)
    public MonetaryAmount installmentInterestOverdue = Money.zero(Monetary.getCurrency("CNY"));
    /*还款金额中还利息罚息的部分*/
    @Builder.Default
    @Convert(converter = LoanMoneyAmountAttributeConverter.class)
    public MonetaryAmount installmentInterestPenalty = Money.zero(Monetary.getCurrency("CNY"));
    /*还款金额中还本金的部分*/
    @Builder.Default
    @Convert(converter = LoanMoneyAmountAttributeConverter.class)
    public MonetaryAmount installmentPrincipal = Money.zero(Monetary.getCurrency("CNY"));
    /*还款金额中还逾期本金的部分*/
    @Builder.Default
    @Convert(converter = LoanMoneyAmountAttributeConverter.class)
    public MonetaryAmount installmentPrincipalOverdue = Money.zero(Monetary.getCurrency("CNY"));

    @ManyToOne
    @JoinColumn(foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    @Convert(converter = LoanContractAttributeConverter.class)
    public LoanContract loanContract;

    @Override
    public String toString(){
        return id;
    }

    public boolean complete(){
        return repaymentAmount
                .subtract(installmentInterest)
                .subtract(installmentInterestOverdue)
                .subtract(installmentInterestPenalty)
                .subtract(installmentPrincipal)
                .subtract(installmentPrincipalOverdue)
                .isEqualTo(Money.zero(Monetary.getCurrency("CNY")));
    }

}
